//
//  NSFileLib.m
//  HandPay
//
//  Created by xy on 10-4-29.
//  Copyright 2010 HANDPAY. All rights reserved.
//

#import "NSFileLib.h"
#import "Directory.h"
#import "Utility.h"
#import "HPClientEngine.h"
#import "StreamEngine.h"
#import "FileUtil.h"
#import "ZZTongDefine.h"

NSArray * getFilesAndDirs(NSString * realpath,BOOL islistsub,NSMutableArray * files,NSString * backPath){
	NSMutableArray * dirs=nil;
	if (islistsub==NO) {
		dirs=[NSMutableArray arrayWithCapacity:10];
	}
	NSFileManager *fileManager = [NSFileManager defaultManager];
	//NSArray * children=[fileManager directoryContentsAtPath:realpath];
	NSArray * children=[fileManager contentsOfDirectoryAtPath:realpath error:nil];
	if (children!=nil && [children count]>0) {
			NSString * temps=nil;
			NSEnumerator * enumi=[children objectEnumerator];
			while (temps=[enumi nextObject]) {
				//fileattr
				NSString * childpath=[realpath stringByAppendingPathComponent:temps];
				NSString * tempchildpath=[backPath stringByAppendingPathComponent:temps];
				BOOL is_direct=YES;
				if ([fileManager fileExistsAtPath:childpath isDirectory:&is_direct]==YES) {
					if (is_direct==YES) {
						if (islistsub==YES) {
							getFilesAndDirs(childpath,islistsub,files,tempchildpath);
						}else {
							[dirs addObject:tempchildpath];
						}
					}else {
						NSFileLib * filedata=[[NSFileLib alloc] init];
						filedata.filepath=tempchildpath;
						//NSDictionary * childinfo=[fileManager fileAttributesAtPath: childpath traverseLink:NO];
						NSDictionary * childinfo=[fileManager attributesOfItemAtPath:childpath error:nil];
						if (childinfo!=nil) {
							filedata.filesize=[[childinfo objectForKey:NSFileSize] intValue];
						}
						[files addObject:filedata];
						[filedata release];
					}
				}
		}
	}
	return dirs;
}

HPData * FileGetRoot(int CanWrite){
	NSString * roots=[Directory getSaveRoot];
	if (roots!=nil) {
		HPData * roodata=CreateTABLEHPData();
		HPData ** datas=(HPData **)malloc(sizeof(HPData *));
		datas[0]= CreateSHPData([roots UTF8String]);
		TableSetArray(roodata,datas,1);
		return roodata;
	}
	return NULL;
}
HPData * FileGetFiles(const char * pathi,int listsub){
	URLStype urltype;
	NSString * roots;
	HPData * resultdata=NULL;
	NSString * path=[Utility TreatUrl:pathi withUrlTpye:&urltype];
	NSString * oripath=path;
	if (path!=nil) {
		if (urltype==UNKNOW_URL) {
			urltype=FILE_URL;
		}
		switch (urltype) {
			case FILE_URL:
				roots=[Directory getFilePath];
				path=[roots stringByAppendingPathComponent:path];
				break;
			case CACHE_URL:
				roots=[Directory getCachePath];
				path=[roots stringByAppendingPathComponent:path];
				break;
			case TEMP_URL:
				roots=[Directory gettempPath];
				path=[roots stringByAppendingPathComponent:path];
				break;	
			default:
				break;
		}
		NSMutableArray * files=[NSMutableArray arrayWithCapacity:10];
		NSArray * dirs= getFilesAndDirs(path,listsub==1?YES:NO,files,oripath);
		
		resultdata=CreateTABLEHPData();
		
		//treat file

		HPData * filestable=CreateTABLEHPData();
		if (files!=nil && [files count]>0) {
			int filenum=[files count];
			HPData ** filesdatas=(HPData **)malloc(sizeof(HPData*)*filenum);
			NSFileLib * tempfilelib=nil;
			NSEnumerator * enumi=[files objectEnumerator];
			int count=0;
			while (tempfilelib=[enumi nextObject]) {
				filesdatas[count]=CreateTABLEHPData();
				HPData ** fdatas=(HPData **)malloc(sizeof(HPData*)*2);
				fdatas[0]=CreateSHPData([tempfilelib.filepath UTF8String]);
				fdatas[1]=CreateNUMHPData(tempfilelib.filesize);
				TableSetArray(filesdatas[count],fdatas,2);
				count++;
			}
			TableSetArray(filestable,filesdatas,filenum);
		}
		TableRawSet(resultdata, "file",filestable);
	
		
		HPData * dirstable=CreateTABLEHPData();
		if (listsub!=1 && dirs!=nil) {//dir
			int dirlen=[dirs count];
			if (dirlen>0) {
				HPData ** dirsdata=(HPData **)malloc(sizeof(HPData *)*dirlen);
				NSString * tempdir=nil;
				NSEnumerator * enumi=[dirs objectEnumerator];
				int count=0;
				while (tempdir=[enumi nextObject]) {
					dirsdata[count]=CreateSHPData([tempdir UTF8String]);
					count++;
				}
				TableSetArray(dirstable,dirsdata,dirlen);
			}			
		}
		TableRawSet(resultdata, "dir",dirstable);
	}
	return resultdata;
}

HPData * FileCreateDir(const char * pathi,const char * namei){
	HPData * resultdata=NULL;
	URLStype urltype;
	NSString * subdirname=[NSString stringWithUTF8String:namei];
	NSString * path=[Utility TreatUrl:pathi withUrlTpye:&urltype];
	NSString * roots=nil;
	NSString * parentname=nil;
	if (path==nil) {
		path=@"";
	}
	NSString * oripath=path;
	if (urltype==UNKNOW_URL) {
		urltype=FILE_URL;
	}
	switch (urltype) {
		case FILE_URL:
			roots=[Directory getFilePath];
			path=[roots stringByAppendingPathComponent:path];
			break;
		case CACHE_URL:
			roots=[Directory getCachePath];
			path=[roots stringByAppendingPathComponent:path];
			break;
		case TEMP_URL:
			roots=[Directory gettempPath];
			path=[roots stringByAppendingPathComponent:path];
			break;	
		default:
			break;
	}
	parentname=[path lastPathComponent];
	path=[path stringByAppendingPathComponent:subdirname];
	oripath=[oripath stringByAppendingPathComponent:subdirname];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	//if ([fileManager createDirectoryAtPath:path attributes:nil]==YES) {
	if ([fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]) {
		resultdata=CreateTABLEHPData();
		HPData * tempdd=CreateSHPData(namei);
		TableRawSet(resultdata, "name",tempdd);
		tempdd=CreateSHPData([parentname UTF8String]);
		TableRawSet(resultdata, "parent",tempdd);
		tempdd=CreateSHPData([oripath UTF8String]);
		TableRawSet(resultdata, "path",tempdd);							
		tempdd=CreateNUMHPData(1);
		TableRawSet(resultdata, "type",tempdd);
	}
	return NULL;
}
int FileExist(const char * pathi){
	int resultdata=0;
	URLStype urltype;
	NSString * roots;
	NSString * path=[Utility TreatUrl:pathi withUrlTpye:&urltype];

	if (path!=nil) {
		if (urltype==UNKNOW_URL) {
			urltype=FILE_URL;
		}
		switch (urltype) {
			case FILE_URL:
				roots=[Directory getFilePath];
				path=[roots stringByAppendingPathComponent:path];
				break;
			case CACHE_URL:
				roots=[Directory getCachePath];
				path=[roots stringByAppendingPathComponent:path];
				break;
			case TEMP_URL:
				roots=[Directory gettempPath];
				path=[roots stringByAppendingPathComponent:path];
				break;	
			default:
				break;
		}
		LOG(@"testfile:%@",path);
		NSFileManager *fileManager = [NSFileManager defaultManager];
		if ([fileManager fileExistsAtPath:path]==YES) {
			resultdata=1;
		}
	}
	return resultdata;
}
void realremove(NSString * path){
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if ([fileManager fileExistsAtPath:path]==YES) {
		[fileManager removeItemAtPath:path error:nil];
	}
}
void FileRemove(const char * pathi){
	URLStype urltype;
	NSString * roots;
	NSString * path=[Utility TreatUrl:pathi withUrlTpye:&urltype];
	
	if (path!=nil) {
		if (urltype==UNKNOW_URL) {
			urltype=FILE_URL;
		}
		HPClientEngine * ce=nil;
		switch (urltype) {
			case FILE_URL:
				roots=[Directory getFilePath];
				path=[roots stringByAppendingPathComponent:path];
				realremove(path);
				break;
			case CACHE_URL:
				roots=[Directory getCachePath];
				path=[roots stringByAppendingPathComponent:path];
				realremove(path);
				break;
			case TEMP_URL:
				roots=[Directory gettempPath];
				path=[roots stringByAppendingPathComponent:path];
				realremove(path);
				break;
			case MEMORY_URL:
				ce=[HPClientEngine getHPClientEngine];
				[ce.se ReleaseMemory:path];
				break;
			default:
				break;
		}
	}
}
int FileRename(const char * pathi,const char * newname){
	int resultdata=0;
	URLStype urltype;
	NSString * roots;
	NSString * path=[Utility TreatUrl:pathi withUrlTpye:&urltype];
	
	if (path!=nil) {
		if (urltype==UNKNOW_URL) {
			urltype=FILE_URL;
		}
		switch (urltype) {
			case FILE_URL:
				roots=[Directory getFilePath];
				path=[roots stringByAppendingPathComponent:path];
				break;
			case CACHE_URL:
				roots=[Directory getCachePath];
				path=[roots stringByAppendingPathComponent:path];
				break;
			case TEMP_URL:
				roots=[Directory gettempPath];
				path=[roots stringByAppendingPathComponent:path];
				break;	
			default:
				break;
		}
		NSFileManager *fileManager = [NSFileManager defaultManager];
		NSString * newpath=[path stringByDeletingLastPathComponent];
		newpath=[newpath stringByAppendingPathComponent:[NSString stringWithUTF8String:newname]];
		if ([fileManager fileExistsAtPath:path]==YES) {
			if ([fileManager moveItemAtPath:path toPath:newpath error:nil]) {
				resultdata=1;
			}
		}
	}
	return resultdata;
}
int FileCopy(const char * oldpathi,const char * newpathi){
	int result=0;
	if (oldpathi!=NULL && newpathi!=NULL) {
		URLStype oldurltype;
		URLStype newurltype;
		NSString * newpath=[Utility TreatUrl:newpathi withUrlTpye:&newurltype];
		NSString * oldpath=[Utility TreatUrl:oldpathi withUrlTpye:&oldurltype];
		HPClientEngine * ce=[HPClientEngine getHPClientEngine];
		if (newurltype==UNKNOW_URL) {
			newurltype=FILE_URL;
		}
		if (oldurltype==UNKNOW_URL) {
			oldurltype=FILE_URL;
		}
		if (oldurltype==RES_URL) {
			NSData * data=[ce.se getData:oldpath withType:oldurltype];
			if (data!=nil) {
				[ce.se saveData:data withurl:newpath withType:FILE_URL];
				result=1;
			}
		}else {
			NSString * roots=nil;
			switch (oldurltype) {
				case FILE_URL:
					roots=[Directory getFilePath];
					oldpath=[roots stringByAppendingPathComponent:oldpath];
					break;
				case CACHE_URL:
					roots=[Directory getCachePath];
					oldpath=[roots stringByAppendingPathComponent:oldpath];
					break;
				case TEMP_URL:
					roots=[Directory gettempPath];
					oldpath=[roots stringByAppendingPathComponent:oldpath];
					break;	
				default:
					break;
			}
			switch (newurltype) {
				case FILE_URL:
					roots=[Directory getFilePath];
					newpath=[roots stringByAppendingPathComponent:newpath];
					break;
				case CACHE_URL:
					roots=[Directory getCachePath];
					newpath=[roots stringByAppendingPathComponent:newpath];
					break;
				case TEMP_URL:
					roots=[Directory gettempPath];
					newpath=[roots stringByAppendingPathComponent:newpath];
					break;	
				default:
					break;
			}
			NSFileManager *fileManager = [NSFileManager defaultManager];
			NSString * dir=[newpath stringByDeletingLastPathComponent];
			if (![fileManager fileExistsAtPath:dir]) {
				[fileManager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
			}		
			NSData * data=[NSData dataWithContentsOfFile:oldpath];
			if (data!=nil) {
				[FileUtil create:newpath withData:data];
				result=1;
			}
		}

	}
	return result;
}
@implementation NSFileLib
@synthesize filepath;
@synthesize filesize;
@end
